package com.demo.arch.datapulsedemo.v2_pipeline.steps;

import com.demo.arch.datapulsedemo.common.OrderData;
import com.demo.arch.datapulsedemo.v2_pipeline.core.PipelineContext;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepExecutionException;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 步骤2：Excel生成处理器
 * 
 * 职责：
 * - 根据查询到的数据生成Excel文件
 * - 将文件路径保存到Context中
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class ExcelGeneratorStepHandler implements StepHandler {

  @Override
  public String getName() {
    return "Excel生成";
  }

  @Override
  public int getOrder() {
    return 2;
  }

  @Override
  public void handle(PipelineContext context) throws StepExecutionException {
    log.info(">>> [{}] 开始执行", getName());

    try {
      List<OrderData> orderList = context.getOrderData();
      String reportType = context.getReportType();

      // 生成文件名
      String timestamp = LocalDateTime.now()
          .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
      String fileName = String.format("%s报表_%s.xlsx", reportType, timestamp);
      String filePath = "/tmp/reports/" + fileName;

      log.info("目标文件: {}", filePath);
      log.info("数据行数: {}", orderList.size());

      // 模拟Excel生成
      generateExcel(orderList, filePath);

      // 保存到Context
      context.setExcelFilePath(filePath);

      log.info(">>> [{}] 完成 -> {}", getName(), filePath);

    } catch (Exception e) {
      log.error(">>> [{}] 执行失败", getName(), e);
      throw new StepExecutionException(getName(), "Excel生成失败", e);
    }
  }

  @Override
  public boolean shouldExecute(PipelineContext context) {
    // 幂等性检查：如果文件已存在且有效，跳过执行
    String filePath = context.getExcelFilePath();
    if (filePath != null) {
      File file = new File(filePath);
      if (file.exists() && file.length() > 0) {
        log.info(">>> [{}] Excel文件已存在，跳过执行: {}", getName(), filePath);
        return false;
      }
    }
    return true;
  }

  /**
   * 生成Excel文件（模拟）
   */
  private void generateExcel(List<OrderData> data, String filePath) {
    log.info("正在创建Excel工作簿...");
    log.info("正在写入表头: [订单编号, 客户名称, 订单金额, 订单时间, 订单状态]");

    // 模拟写入过程
    try {
      Thread.sleep(50);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }

    log.info("正在保存Excel文件...");
  }
}
